/**
 * 选择语言
 */
import * as types from '../mutation_types.js'
import ls from 'store2'
import api from '@/service'

const state = {
  token: '',
  info: ls.get('info') || {
    source_app: '',
    user_id: '0',
    idfa: ''
  },
  appinfo: ls.get('appinfo') || {}
}

const mutations = {
  [types.SET_TOKEN] (state, token) {
    state.token = token
  },
  [types.CLEAR_TOKEN] (state) {
    state.token = ''
  },
  [types.SET_INFO] (state, info) {
    state.info = {
      ...state.info,
      ...info
    }
    ls.set('info', state.info)
  },
  [types.GET_APPINFO] (state, appinfo) {
    state.appinfo = appinfo
    ls.set('appinfo', appinfo)
  }
}

const actions = {
  setToken ({ commit }, token) {
    commit(types.SET_TOKEN, token)
  },
  clearToken ({ commit }) {
    commit(types.CLEAR_TOKEN)
  },
  setInfo ({ commit }, info) {
    commit(types.SET_INFO, info)
  },
  getAppinfo ({ commit }, appinfo) {
    return api.get('http://118.178.236.36:8090/admin/assistant/opening').then(req => {
      let appinfo = {}
      appinfo[''] = '短信'
      appinfo['sms_cp'] = '短信-产品'
      appinfo['diaoqianyaner'] = '掉钱眼儿'
      appinfo['web_push'] = '网站推广'
      appinfo['com.cq.duke.nomoneyme'] = '没钱了么-Android'
      appinfo['push'] = '推广'
      appinfo['push_android'] = '推广-Android'
      appinfo['push_ios'] = '推广-IOS'
      for (let item of req) {
        appinfo[item.source_app] = item.app_name
      }
      commit(types.GET_APPINFO, appinfo)
    })
  }
}

const getters = {
  token: state => state.token,
  info: state => state.info,
  appinfo: state => state.appinfo,
  appname: state => state.appinfo[state.info.source_app] || '其他'
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
